package com.sq.bootshiro.modules.controller;


import com.sq.bootshiro.common.utils.Constant;
import com.sq.bootshiro.common.utils.IPUtils;
import com.sq.bootshiro.modules.dto.LoginDTO;
import com.sq.bootshiro.modules.entity.LogUserLogin;
import com.sq.bootshiro.modules.entity.User;
import com.sq.bootshiro.modules.service.IShiroService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "接口服务", value = "/api/v1/swagger/**")
@RestController
public class ShiroController {

    @Autowired
    private IShiroService shiroService;

    /**
     * 登录
     */

    @ApiOperation("登陆")
    @PostMapping("/sys/login")
    public Map<String, Object> login(@RequestBody @Validated LoginDTO loginDTO, BindingResult bindingResult, HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        String loginStatus = Constant.LogUserLoginStatus.FAIL.getValue();

        if (bindingResult.hasErrors()) {
            result.put("status", 400);
            result.put("msg", bindingResult.getFieldError().getDefaultMessage());
            return result;
        }

        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();


        //用户信息
        User user = shiroService.findUserByUsername(username);
        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(password)) {
            result.put("status", 400);
            result.put("msg", "账号或密码有误");
        } else {
            //生成token，并保存到数据库
            result = shiroService.createToken(username, password);


            result.put("status", 200);
            result.put("msg", "登陆成功");
            loginStatus = Constant.LogUserLoginStatus.SUCCESS.getValue();
        }

        User userByUsername = shiroService.findUserByUsername(username);

        LogUserLogin logUserLogin = LogUserLogin.builder()
                .loginTime(LocalDateTime.now())
                .loginIp(IPUtils.getIpAddr(request))
                .loginRemark(result.get("msg").toString())
                .loginStatus(loginStatus)
                .build();
//        if (userByUsername != null) {
            logUserLogin.setUserId(userByUsername.getUserId() + "");
//        }

        shiroService.insertLogUserLogin(logUserLogin);

        return result;


    }

    /**
     * 退出
     */
    @ApiOperation(value = "登出", notes = "参数:token")
    @PostMapping("/sys/logout")
    // PrincipalCollection principals
    public Map<String, Object> logout(@RequestHeader("token") String token) {
        Map<String, Object> result = new HashMap<>();
        shiroService.logout(token);
        result.put("status", 200);
        result.put("msg", "您已安全退出系统");
        return result;
    }

//    @ApiOperation(value = "未登录", notes = "参数:无 ")
//    @GetMapping("/unlogin")
//    public Map<String, Object> unlogin() {
//        Map<String, Object> map = new HashMap();
//        map.put("status", 404);
//        map.put("msg","未登录");
//        return map;
//    }


}
